package com.xingxin.controller;


import com.xingxin.entity.Permission;
import com.xingxin.entity.Role;
import com.xingxin.service.PermissionService;
import com.xingxin.service.RoleService;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author mrLiu
 * @since 2021-01-08
 */
@Controller
@RequestMapping("/role")
public class RoleController extends BaseController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private PermissionService permissionService;

    /**
     * 查询权限列表
     *
     * @return
     */
    @GetMapping("/query")
    @ResponseBody
    public Map<String, Object> queryRoles() {
        logger.info("==>RoleController--queryRoles()--start. ");
        List<Map<String, Object>> data = new ArrayList<>();
        try {
            List<Role> roles = roleService.list();
            if (CollectionUtils.isEmpty(roles)) return this.resultMap("-1", "result is null", null);
            roles.forEach(role -> {
                Map<String, Object> roleMap = new HashMap<>();
                List<String> psIdList = Arrays.asList(role.getPsIds().split(","));
                roleMap.put("roleId", role.getRoleId());
                roleMap.put("roleName", role.getRoleName());
                roleMap.put("roleDesc", role.getRoleDesc());
                List<Permission> permissions = permissionService.getBaseMapper().selectBatchIds(psIdList);
                List<Permission> permissionNewList = permissions.stream().filter(permission -> StringUtils.equals("0", permission.getPsLevel())).collect(Collectors.toList());
                roleMap.put("children", permissionNewList);
                data.add(roleMap);
            });
            return resultMap("0", "success", data);
        } catch (Exception e) {
            logger.error("==>RoleController--queryRoles()--Exception: {}", e);
            return resultMap("-1", "Exception", null);
        }
    }

    /**
     * 根据id查询用户权限
     *
     * @param roleId
     */
    @GetMapping("/queryById")
    @ResponseBody
    public Map<String, Object> queryRoleById(@RequestParam("roleId") String roleId) {
        logger.info("==>RoleController--queryRoleById--start,params is : {}", roleId);
        List<Integer> powerList = new ArrayList<>();
        Map<String, Object> resultMap;
        try {
            if (StringUtils.isBlank(roleId)) return resultMap("-1", "params is null", null);
            Role role = roleService.getBaseMapper().selectById(roleId);
            if (Objects.isNull(role)) return resultMap("-1", "result is null", null);
            List<String> psIds = Arrays.asList(role.getPsIds().split(","));
            List<Permission> permissions = permissionService.getBaseMapper().selectBatchIds(psIds);
            List<Permission> permissionNewList = permissions.stream()
                    .filter(permission -> StringUtils.equals("0", permission.getPsLevel()))
                    .collect(Collectors.toList());
            permissionNewList.forEach(permission -> powerList.add(permission.getPsId()));
            logger.info("==>RoleController--queryRoleById--over, result is : {}", powerList);

            resultMap = this.resultMap("0", "success", powerList);
        } catch (Exception e) {
            logger.error("==>RoleController--queryRoleById--Exception is: {}", e);
            resultMap = this.resultMap("-1", "Exception", null);
        }
        return resultMap;
    }


    /**
     * 删除用户权限
     *
     * @param psId
     * @return
     */
    @GetMapping("/deletePower")
    @ResponseBody
    public Map<String, Object> deletePowerByPsId(@RequestParam("id") Integer id, @RequestParam("psId") String psId) {
        StringBuffer sb = new StringBuffer();
        Role roleNew = new Role();
        try {
            Role role = roleService.getBaseMapper().selectById(id);
            if (null == role || StringUtils.isBlank(role.getPsIds())) {
                return resultMap("-1", "用户权限为空", null);
            }
            List<String> psIdList = Arrays.asList(role.getPsIds().split(","));
            List<String> psIdNewList =
                    psIdList.stream().filter(p -> !StringUtils.equals(p, psId)).collect(Collectors.toList());
            psIdNewList.forEach(p -> sb.append(p + ","));
            if(psIdNewList.size()==0) roleNew.setPsIds("");
            roleNew.setPsIds(sb.substring(0, sb.length() - 1));
            roleNew.setRoleId(id);
            boolean b = roleService.updateById(roleNew);
            if (b) {
                return resultMap("0", "success", null);
            }
            return resultMap("-1", "删除用户权限失败", null);
        } catch (Exception e) {
            logger.error("==>RoleController--deletePowerByPsId()--Exception is: {}", e);
            return resultMap("-1", "Exception", e.getMessage());
        }
    }

    /**
     * 更新用户权限
     */
    @PostMapping("/update")
    @ResponseBody
    public Map<String, Object> updatePowerListById(@RequestBody Map<String, Object> inMap) {
        logger.info("==>RoleController--updatePowerListById--start, params is : {}", inMap);
        Role role = new Role();
        StringBuffer psIds = new StringBuffer();
        try {
            if (MapUtils.isEmpty(inMap) || Objects.isNull(inMap.get("roleId"))
                    || Objects.isNull(inMap.get("powerList"))) {
                return resultMap("-1", "params is null", null);
            }
            if (!(inMap.get("roleId") instanceof Integer)
                    || !(inMap.get("powerList") instanceof List)
                    || (((List) inMap.get("powerList")).size()==0)) {
                return resultMap("-1", "params type error", null);
            }
            role.setRoleId((Integer) inMap.get("roleId"));
            List powerList = (List) inMap.get("powerList");
            powerList.forEach(p -> psIds.append(p + ","));
            role.setPsIds(psIds.substring(0, psIds.length() - 1));
            boolean b = roleService.updateById(role);
            if (b) {
                return resultMap("0", "success", null);
            }
            return resultMap("-1", "update failed", null);
        } catch (Exception e) {
            logger.error("==>RoleController--updatePowerListById--Exception : {}", e);
            return resultMap("-1", "Exception", e);
        }
    }
}

